import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { useRoute, useRouter } from "vue-router";

const storeSetup = () => {
  const route = useRoute();
  const router = useRouter();
  /* 定义数据--------------------------------------------------------------------- */
  // 菜单列表
  const menus = ref([]);

  // 当前选择的菜单key
  const selectedKeys = ref(["0", "0-1"]);

  // 面包屑列表
  const breadcrumbs = ref([]);

  /* 定义函数--------------------------------------------------------------------- */
  // 获取菜单
  const getMenus = () => {
    let notHideRoutes = filterHide(
      route.matched.find((route) => (route.name = "Layout")).children
    );
    let newMenus = routesToMenus(notHideRoutes);
    menus.value = newMenus;
  };

  // 选择菜单
  const selectMenu = (menuType, menuItem) => {
    selectedKeys.value = [menuType.key, menuItem.key];

    // 过滤数据
    let toPath;
    let newBreadcrumbs = [];
    menus.value.forEach((menuT) => {
      if (menuT.key == menuType.key) {
        newBreadcrumbs.push(menuT);
        menuT.children.forEach((menuI) => {
          if (menuI.key == menuItem.key) {
            newBreadcrumbs.push(menuI);
            toPath = menuI.path;
          }
        });
      }
    });

    breadcrumbs.value = newBreadcrumbs;
    router.push({
      path: toPath,
    });
  };

  // 路由表转换菜单格式
  const routesToMenus = (routes) => {
    return routes.map((routeItem) => {
      if (routeItem.children) {
        routeItem.children = routesToMenus(routeItem.children);
      }
      return {
        key: routeItem.meta.key,
        icon: routeItem.meta.icon,
        label: routeItem.meta.title,
        title: routeItem.meta.title,
        path: routeItem.path,
        children:
          routeItem.children.length == 0 ? undefined : routeItem.children,
      };
    });
  };

  // 过滤不进行菜单显示的路由项
  const filterHide = (routes) => {
    let newMenus = [];
    routes.forEach((routeItem) => {
      if (!routeItem.meta.isHide) {
        const children = routeItem.children
          ? filterHide(routeItem.children)
          : [];
        newMenus.push({ ...routeItem, children });
      }
    });
    return newMenus;
  };

  // 返回参数
  return { menus, selectedKeys, breadcrumbs, selectMenu, getMenus };
};

// 导出Store
export const useRouterStore = defineStore("router", storeSetup, {
  persist: true,
});
